﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoginController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The login controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Security;
    using Website.CRUDServices;
    using Website.InitializerService;
    using Website.Models;
    using User = Website.Models.Domain.User;

    /// <summary>
    ///     The login controller.
    /// </summary>
    public class LoginController : Controller
    {
        // GET: /Login/
        #region Public Methods and Operators

        /// <summary>
        ///     The index.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult Index()
        {
            this.Session["LoggedInUser"] = null;
            this.Session.Abandon();

            //using (var client = new InitializerServiceClient())
            //{
            //    client.Update();
            //}

            return this.View();
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="username">
        /// The username.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        public ActionResult Index(string username, string password)
        {
            // create a global user object for the logged in user
            var theUser = new User { Username = username, Password = password.Trim() };
            this.Session["LoggedInUser"] = theUser;

            return CRUDServiceProvider.WithCRUDService<ActionResult>(
                client =>
                {
                    var query = new ValidateUserQuery { Username = username, Password = password };

                    IResult res = client.Query(query);

                    if (!(res.GetType() == typeof(ValidateUserResult)))
                    {
                        this.ViewData["ErrorMessage"] = "Brugernavn eller password er forkert.";
                        return this.View();
                    }

                    var result = (ValidateUserResult)client.Query(query);

                    if (result != null && result.InvalidUsernameOrPassword == false && result.UserID != Guid.Empty)
                    {
                        this.Session["UserID"] = result.UserID;

                        var uq = new UsersQuery { Settings = new SearchSettings { IDEquals = result.UserID } };

                        var urs = (UsersResult)client.Query(uq);
                        if (urs.List.Any())
                        {
                            CRUDServices.User serviceUser = urs.List[0];
                            theUser.Name = serviceUser.Name;
                            theUser.PhoneNumber = serviceUser.PhoneNumber;
                            theUser.Username = serviceUser.Username;
                            theUser.Email = serviceUser.Email;
                            theUser.ID = serviceUser.ID;
                            this.Session["LoggedInUser"] = theUser;
                            FormsAuthentication.SetAuthCookie(theUser.Username, false);

                            
                            return this.RedirectToAction("Index", "Home");
                        }

                    }

                    this.ViewData["ErrorMessage"] = "Brugernavn eller password er forkert.";
                    return this.View();
                });
        }

        #endregion
    }
}